#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<fcntl.h>
#include<assert.h>

#define NUM 256
struct my_file
{
    int fd;
    char buffer[NUM];//缓冲区
    int end;//缓冲区结尾标志
};

typedef struct my_file MyFile;

MyFile* fopen_(const char* pathname,const char* mode)
{
    assert(pathname);
    assert(mode);
    
    MyFile*fp = NULL;
    if(!strcmp(mode,"w"))
    {
        int fd =  open(pathname,O_WRONLY | O_CREAT | O_TRUNC,0666);
        if(fd>=0)
        {
            fp = (MyFile*)malloc(sizeof( MyFile));
            memset(fp,0,sizeof(MyFile));
            fp->fd = fd; 
        }
    }
    else if(strcmp(mode,"a")) {}
    else if(strcmp(mode,"a+")){}
    else if(strcmp(mode,"w+")){}
    else if(strcmp(mode,"r")){}
    else if(strcmp(mode,"r+")){}
    else {}
    return fp;
}

void fputs_(const char* message,MyFile* fp)
{
    assert(message);
    assert(fp);

    strcpy(fp->buffer+fp->end,message);
    fp->end+=strlen(message);

    if(fp->fd == 0){}
    else if(fp->fd ==1)
    {
        if(*(fp->buffer+fp->end-1)=='\n')
        {
            write(1,fp->buffer,fp->end);
            fp->end = 0;
        }
    }
    else if(fp->fd==2)
    {}
    else{}
}

void fflush_(MyFile* fp)
{
    assert(fp);
    if(fp->end!=0)
    {
        write(fp->fd,fp->buffer,fp->end);
        syncfs(fp->fd);
        fp->end =0;
    }
}

void fclose_(MyFile* fp)
{
    assert(fp);
    fflush_(fp);
    close(fp->fd);
    free(fp);
}
int main()
{
    close(1);
    MyFile* fp = fopen_("./log3.txt","w");
    if(fp==NULL)
    {
        printf("fopen_:");
        return 1;
    }

    fputs_("one test for my file function",fp);
    fputs_("two test for my file function\n",fp);
    fputs_("three test for my file function",fp);
    fputs_("four test for my file function\n",fp);


    fork();
    fclose_(fp);
    return 0;
}
